const express = require("express");
const static = require('serve-static');
const bodyParer  = require('body-parser');
const app = express();
const router = express.Router();
const fs = require('fs');
const path = require('path');

router.get("/", function (req, res) {
    //返回index.html
    res.writeHead(302, {"Content-Type": "text/html;charset=utf-8", 'Location': 'http://127.0.0.1:3000/test/index.html'});
    res.end();
});

router.get("/test/*", function (req, res) {
    var splits = req.url.split('/test/');
    var filename = splits[splits.length-1];
    var url = path.join(__dirname, '../test', filename.split('?')[0]);
    if (filename.indexOf('.html') !== -1) {
        res.header("Content-Type", "text/html; charset=utf-8");
    } else if (filename.indexOf('.js') !== -1) {
        res.header("Content-Type", "application/javascript; charset=utf-8");
    } else if (filename.indexOf('.css') !== -1) {
        res.header("Content-Type", "text/css; charset=utf-8");
        res.header("Cache-Control", "max-age:315360000");
    } else if (filename.indexOf('.png') !== -1) {
        res.header("Content-Type", "image/png");
    } else if ( filename.indexOf('.jpg') !== -1) {
        res.header("Content-Type", "image/jpeg");
    }

    return res.sendFile(url);

});

router.get("/static/*", function (req, res) {
    var splits = req.url.split('/static/');
    var filename = splits[splits.length-1];
    var url = path.join(__dirname, '../static', filename.split('?')[0]);
    if (filename.indexOf('.html') !== -1) {
        res.header("Content-Type", "text/html; charset=utf-8");
    } else if (filename.indexOf('.js') !== -1) {
        res.header("Content-Type", "application/javascript; charset=utf-8");
    } else if (filename.indexOf('.css') !== -1) {
        res.header("Content-Type", "text/css; charset=utf-8");
        res.header("Cache-Control", "max-age:315360000");
    } else if (filename.indexOf('.png') !== -1) {
        res.header("Content-Type", "image/png");
    } else if ( filename.indexOf('.jpg') !== -1) {
        res.header("Content-Type", "image/jpeg");
    }

    return res.sendFile(url);

});

function cal(a) {
    var a = Number(a) || 0;
    const data = {
        code : 0,
        data: {
            a: a,
            b: a * 2
        }
    };
    return data;
}

router.post("/calculate", function (req, res) {
    res.header("Content-Type", "application/json; charset=utf-8");
    const data = cal(req.body.a);
    res.status(200).send(data);

});


router.get("/calculate", function (req, res) {
    res.header("Content-Type", "application/json; charset=utf-8");
    const data = cal(req.query.a);
    res.status(200).send(data);
});


module.exports = router;